<template>
    <nav-bar categoryName="顺序练习"></nav-bar>
    <div class="ad">
        <van-image :src="banner" fit="contain"></van-image>
    </div>
    <!-- 考题 -->
    <div class="content">
        <div class="question">
            <div class="question-title">{{ questionDetail.question }}</div>
        </div>
        <div class="option">

            <!-- 单选或判断 -->
            <van-radio-group v-model="selected" shape="square"
                v-if="questionDetail.optionType === 0 || questionDetail.optionType === 1">
                <template v-for="(optionKey, index) in Object.keys(questionDetail.options)" :key="index">
                    <template v-if="questionDetail.options[optionKey]">
                        <van-radio :name="answerRateToOptions[index].answer">
                            <template #icon="props">
                                <van-image :src="right" class="icon"
                                    v-if="confirmed && answerRateToOptions[index].answer === questionDetail.answer"></van-image>
                                <div class="icon" :class="props.checked ? 'active' : 'inactive'" v-else>
                                    {{ answerRateToOptions[index].option }}
                                </div>
                            </template>
                            <span> {{ questionDetail.options[optionKey] }}</span>
                        </van-radio>
                    </template>
                </template>
            </van-radio-group>


            <!-- 多选题 -->
            <van-checkbox-group v-model="selected" shape="square" ref="checkboxes"
                v-if="questionDetail.optionType === 2">
                <template v-for="(optionKey, index) in Object.keys(questionDetail.options)" :key="index">
                    <template v-if="questionDetail.options[optionKey]">
                        <van-checkbox :name="answerRateToOptions[index].answer" :id="answerRateToOptions[index].answer">
                            <template #icon="props">

                                <van-image :src="right" class="icon"
                                    v-if="confirmed && answerRateToOptions[index].answer === questionDetail.answer"></van-image>

                                <div class="icon" :class="props.checked ? 'active' : 'inactive'" v-else>
                                    {{ answerRateToOptions[index].option }}
                                </div>
                            </template>
                            <span> {{ questionDetail.options[optionKey] }}</span>
                        </van-checkbox>
                    </template>
                </template>
            </van-checkbox-group>
        </div>
        <div class="confirm">
            <van-button class="confirm-btn" round @click="submitAnswer">提交 </van-button>
        </div>
        <div class="explain"></div>
    </div>
</template>
<script setup>
import right from "/assets/right.png"
import NavBar from "@/components/common/navbar/NavBar.vue";
import banner from "@/assets/ad/jkbd.png";
import { fetchSequence, fetchQuestion, fetchQuestions } from "@/api/index.js"; //顺序练习API
import { ref, reactive, toRefs, watch, onMounted, useTemplateRef } from "vue";

const checkboxesRef = useTemplateRef('checkboxes')

import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
import { useStore } from "@/pinia/index.js";
const store = useStore();
const selected = ref([]) // [16,32,64,128]
const confirmed = ref(false)
const state = reactive({
    carType: route.params.carType,
    course: route.params.course,
    cityCode: store.currentCity.code,
});
const questionDetail = reactive({
    question: "", //问题
    answer: "",   //答案值
    assuredKeywords: "",
    conciseExplain: "", //简明解释
    explain: "",
    illiteracyExplain: "", //文盲解释
    illiteracyKeywords: "",
    keywords: "",
    knackDetail: "", //诀窍
    knackKeyword: "",
    knackVoiceTxt: "",
    optionType: 0, //单选或者多选
    options: {
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        optionE: "",
        optionF: "",
        optionG: "",
        optionH: ""
    }
})
const allQuestionIds = ref([])
const questionId = ref()
onMounted(async () => {
    await getSequenceQuestion(state.carType, state.course, state.cityCode)
    //  每次从questionIds.value 获取1个问题id
    questionId.value = allQuestionIds.value.splice(0, 1)
    await getQuestionDetail(questionId.value) //获取1个问题详情
})
//获取顺序练习全部questionID
const getSequenceQuestion = async (carType, course, cityCode) => {
    const { questionIds } = await fetchSequence(carType, course, cityCode);
    allQuestionIds.value = questionIds
    // console.log(allQuestionIds.value);
};
const answerRateToOptions = ref([
    { answer: 16, option: 'A' },
    { answer: 32, option: 'B' },
    { answer: 64, option: 'C' },
    { answer: 128, option: 'D' },
])
// 获取题目详情
const getQuestionDetail = async (questionId) => {
    const response = await fetchQuestion(questionId);
    const {
        question,
        answer,
        assuredKeywords,
        conciseExplain,
        explain,
        illiteracyExplain,
        illiteracyKeywords,
        keywords,
        knackDetail,
        knackKeyword,
        knackVoiceTxt,
        optionType,
        optionA,
        optionB,
        optionC,
        optionD,
        optionE,
        optionF,
        optionG,
        optionH,
    } = response[0]
    questionDetail.question = question;
    questionDetail.answer = answer;
    questionDetail.assuredKeywords = assuredKeywords;
    questionDetail.conciseExplain = conciseExplain;
    questionDetail.explain = explain;
    questionDetail.illiteracyExplain = illiteracyExplain;
    questionDetail.illiteracyKeywords = illiteracyKeywords;
    questionDetail.keywords = keywords;
    questionDetail.knackDetail = knackDetail;
    questionDetail.knackKeyword = knackKeyword;
    questionDetail.knackVoiceTxt = knackVoiceTxt;
    questionDetail.optionType = optionType;     // 0 判断题  1 单选 2 多选

    // 更新选项值
    //答案文案
    questionDetail.options.optionA = optionA;
    questionDetail.options.optionB = optionB;
    questionDetail.options.optionC = optionC;
    questionDetail.options.optionD = optionD;
    questionDetail.options.optionE = optionE;
    questionDetail.options.optionF = optionF;
    questionDetail.options.optionG = optionG;
    questionDetail.options.optionH = optionH;
};

// 提交答案
const submitAnswer = () => {

    // 本地提交的答案序号
    console.log("selected", selected.value)  // 16，32，64，128

    //判断或者单选题取消选中的选项
    if (questionDetail.optionType == 0 || questionDetail.optionType == 1) {
        for (let i = 0; i < answerRateToOptions.value.length; i++) {
            selected.value = []

        }
    }



    // 多选题，取消选中的选项
    if (questionDetail.optionType == 2 && checkboxesRef.value) {
        checkboxesRef.value.toggleAll(false)
    }



    //正确答案
    const rightAnswer = questionDetail.answer;

    //高亮正确的答案，将正确选项的icon换成right图片
    // 如果是单选题，则直接高亮对应的选项，如果是多选题，则需要票将正确答案拆分出来，备选的选项值分别是16，32，64，128。假设正确答案是48，由于16+32=48.所以对应的第一和第二个选项是正确答案
    // 需要将正确答案对应的icon换成right图片

    // 如果是判断或者单选题，则需要将正确答案对应的icon换成right图片
    if (questionDetail.optionType == 0 || questionDetail.optionType == 1) {
        for (let i = 0; i < answerRateToOptions.value.length; i++) {
            if (answerRateToOptions.value[i].answer === rightAnswer) {
                confirmed.value = true;
            }
        }
    }

    //如果是多选题，则需要将正确答案对应的icon换成right图片
    if (questionDetail.optionType == 2) {






    }






};





const matchAnswer = (correct_answer) => {
    // 存储所有可能的组合索引
    const resultIndexes = [];
    // 获取所有有效的选项（answer值存在的选项）
    const validOptions = answerRateToOptions.value.filter(option => option.answer);


    // 生成所有可能的组合并检查哪些组合的和等于目标值
    const findCombinations = (startIndex, currentSum, currentIndexes) => {
        // 如果当前和等于目标值，保存这个组合
        if (currentSum === correct_answer) {
            resultIndexes.push([...currentIndexes]);
            return;
        }

        // 如果当前和已经超过目标值，或者已经检查完所有选项，则返回
        if (currentSum > correct_answer || startIndex >= validOptions.length) {
            return;
        }

        // 遍历剩余的选项
        for (let i = startIndex; i < validOptions.length; i++) {
            const option = validOptions[i];
            // 添加当前选项到组合中
            currentIndexes.push(i);
            // 递归查找
            findCombinations(i + 1, currentSum + option.answer, currentIndexes);
            // 回溯，移除当前选项
            currentIndexes.pop();
        }
    };

    // 开始查找组合
    findCombinations(0, 0, []);

    // 返回第一个找到的组合（通常应该只有一个正确答案组合）

    console.log("resultIndexes", resultIndexes)
    return resultIndexes.length > 0 ? resultIndexes[0] : [];


};








</script>
<style scoped lang="scss">
.content {
    padding: 10px;

    .question {
        margin-bottom: 30px;

        .question-title {
            color: #333;
            font-size: 20px;
            text-align: left;
        }
    }

    .option {

        .van-checkbox,
        .van-radio {
            margin: 10px;
            display: flex;
            align-items: center;

            :deep(.van-checkbox__icon),
            :deep(.van-radio__icon) {
                height: auto !important;

                .icon {
                    // 圆形样式
                    width: 40px;
                    height: 40px;
                    border-radius: 50%; // 确保是完美的圆形
                    background-color: #fff;
                    border: 1px solid #999;
                    margin-right: 10px;
                    // 使用 flex 布局实现文字水平垂直居中
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    // 文字样式
                    font-size: 16px;
                    color: #999;

                    &.active {
                        background-color: #18b4ed;
                        border: 1px solid #18b4ed;
                        color: #fff;
                    }

                    &.inactive {
                        color: #999;
                        background-color: #fff;
                        border: 1px solid #999;
                    }
                }
            }
        }
    }

    .confirm {
        margin-top: 20px;

        .confirm-btn {
            width: 110px;
            height: 30px;
            background-color: #18b4ed;
            border-radius: 4px;
            font-size: 16px;
            color: #fff;
        }
    }

    .explain {}
}
</style>